# -*- coding: utf-8 -*-
"""
Created on Wed Dec 20 14:40:07 2017

@author: win7
"""

import socket
import sys
import binascii
import time
import threading
import queue
import os
import string
#import cv2



#devLogoMsg = b'\x55\xaa\x54\x00\x00\x00\x03\x20\x67\x73\x76\x32\x75\x30\x30\x33\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\xa8\x62\x67\x73\x76\x32\x75\x30\x30\x33\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
#devLogoMsg = b"\x55\xaa\x54\x00\x00\x00\x03\x20\x67\x73\x76\x32\x75\x30\x30\x33\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\xa8\x62\x67\x73\x76\x32\x75\x30\x30\x33\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
devheartbeatMsg = b"\x55\xaa\x00\x00\x00\x00\x01\x00"
devWorkStatusMsg = b"\x55\xaa\x04\x00\x00\x00\x00\xa8\x00\x00\x00\x00"
devUpdateAlarmMsg = b"\x55\xaa\x26\x01\x00\x00\x01\x0c\x3c\x52\x6f\x6f\x74\x3e\x3c\x50\x61\x74\x3e\x3c\x52\x65\x71\x41\x6c\x61\x72\x6d\x56\x69\x64\x65\x6f\x3e\x3c\x41\x6c\x61\x72\x6d\x49\x64\x3e\x53\x54\x52\x2c\x30\x7c\x3c\x2f\x41\x6c\x61\x72\x6d\x49\x64\x3e\x3c\x49\x70\x3e\x53\x54\x52\x2c\x31\x33\x7c\x31\x31\x38\x2e\x32\x36\x2e\x32\x33\x2e\x31\x30\x34\x3c\x2f\x49\x70\x3e\x3c\x50\x6f\x72\x74\x3e\x53\x33\x32\x2c\x30\x2c\x36\x35\x35\x33\x35\x7c\x33\x39\x37\x39\x3c\x2f\x50\x6f\x72\x74\x3e\x3c\x41\x6c\x61\x72\x6d\x4e\x75\x6d\x62\x65\x72\x3e\x53\x54\x52\x2c\x31\x36\x7c\x30\x34\x30\x30\x30\x32\x30\x30\x30\x30\x31\x36\x33\x35\x37\x38\x3c\x2f\x41\x6c\x61\x72\x6d\x4e\x75\x6d\x62\x65\x72\x3e\x3c\x44\x62\x49\x70\x3e\x53\x54\x52\x2c\x31\x32\x7c\x31\x30\x2e\x31\x34\x33\x2e\x35\x37\x2e\x31\x32\x3c\x2f\x44\x62\x49\x70\x3e\x3c\x44\x62\x50\x6f\x72\x74\x3e\x53\x33\x32\x2c\x30\x2c\x36\x35\x35\x33\x35\x7c\x37\x38\x38\x37\x3c\x2f\x44\x62\x50\x6f\x72\x74\x3e\x3c\x41\x6c\x61\x72\x6d\x45\x76\x65\x6e\x74\x3e\x53\x54\x52\x2c\x34\x7c\x33\x34\x34\x31\x3c\x2f\x41\x6c\x61\x72\x6d\x45\x76\x65\x6e\x74\x3e\x3c\x45\x72\x72\x2f\x3e\x3c\x2f\x52\x65\x71\x41\x6c\x61\x72\x6d\x56\x69\x64\x65\x6f\x3e\x3c\x2f\x50\x61\x74\x3e\x3c\x2f\x52\x6f\x6f\x74\x3e"

#devLogoMsg = "\x55\xaa\x54\x00\x00\x00\x03\x20"+accountstr+accountstr+"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"

#serverHost = "192.168.137.1"
serverHost = "118.26.23.97"#"118.184.176.34"
serverPort = 7779#11103


print ("connect server")

xmlAlramSting = b"!paT5001XMLD0124000000000464000000000464<Root><UpLoad><AlarmInfo><Cid>STR,4|3441</Cid><Time>DTA,19|2010.01.01.00.00.24</Time><AlarmId>STR,14|F37DAE9E06692D</AlarmId><AreaNo>U32,0,65535|1</AreaNo><AreaName>STR,4|Hall</AreaName><UserNo>U32,0,65535|18</UserNo><UserName>STR,3|cms</UserName><LoginType>TYP,CMS|2</LoginType><Longitude>STR,3|0.0</Longitude><Latitude>STR,3|0.0</Latitude><Height>STR,3|0.0</Height><Channel>S32,0,65535|0</Channel><WanIp>STR,15|192.168.137.164</WanIp></AlarmInfo></UpLoad></Root>0464"
#外出布防
xmlAlramSting1 = b"!paT5001XMLD0124000000000464000000000464<Root><UpLoad><AlarmInfo><Cid>STR,4|3401</Cid><Time>DTA,19|2010.01.01.00.00.24</Time><AlarmId>STR,14|F37DAE9E06692D</AlarmId><AreaNo>U32,0,65535|1</AreaNo><AreaName>STR,4|Hall</AreaName><UserNo>U32,0,65535|18</UserNo><UserName>STR,3|cms</UserName><LoginType>TYP,CMS|2</LoginType><Longitude>STR,3|0.0</Longitude><Latitude>STR,3|0.0</Latitude><Height>STR,3|0.0</Height><Channel>S32,0,65535|0</Channel><WanIp>STR,15|192.168.137.164</WanIp></AlarmInfo></UpLoad></Root>0464"
#
xmlAlramSting2 = b"!paT5001XMLD0124000000000464000000000464<Root><UpLoad><AlarmInfo><Cid>STR,4|1401</Cid><Time>DTA,19|2010.01.01.00.00.24</Time><AlarmId>STR,14|F37DAE9E06692D</AlarmId><AreaNo>U32,0,65535|1</AreaNo><AreaName>STR,4|Hall</AreaName><UserNo>U32,0,65535|18</UserNo><UserName>STR,3|cms</UserName><LoginType>TYP,CMS|2</LoginType><Longitude>STR,3|0.0</Longitude><Latitude>STR,3|0.0</Latitude><Height>STR,3|0.0</Height><Channel>S32,0,65535|0</Channel><WanIp>STR,15|192.168.137.164</WanIp></AlarmInfo></UpLoad></Root>0464"
#报警消息推送
xmlAlramSting3 = b'!paT5001XMLD0124000000000523000000000523<Root><UpLoad><AlarmInfo><Cid>STR,4|1131</Cid><Time>DTA,19|2018.07.25.16.39.33</Time><AlarmId>STR,14|F37DAE8D3DED36</AlarmId><AreaNo>U32,0,65535|1</AreaNo><AreaName>STR,4|Hall</AreaName><DevNo>U32,0,65535|1</DevNo><DevName>STR,6|</DevName><DevType>TYP,DOOR_SENSOR|10</DevType><RfId>STR,9|230001001</RfId><WlId>STR,9|230001001</WlId><Longitude>STR,3|0.0</Longitude><Latitude>STR,3|0.0</Latitude><Height>STR,3|0.0</Height><Channel>S32,0,65535|0</Channel><WanIp>STR,15|192.168.137.164</WanIp></AlarmInfo></UpLoad></Root>0523'
def createSocket():
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    s.connect((serverHost,serverPort))
    return s

def recvServerData(Qd,s,id):
    while True:
        try:
            data = s.recv(4096)
            Qd.put(data)
            #print("net recv thread")
        except Exception:
           break

def processData(cq,Qd,id):
    runOnes = 0
    while True:
        try:
            s = createSocket()
            th2 = threading.Thread(target=recvServerData,args=(Qd,s,id))
            th2.start()
            if runOnes == 0:
                print(id,"准备就绪")
                #cq.get()#等待命令
            runOnes = 1
            account = id.encode()
            #account = b"gm123456" #设备账号
            devLogoMsg =  b"U\xaaT\x00\x00\x00\x03 "+account+b"\x00\x00\x00\x00\x00\x00\x00\x00\x01\x126@"+account+b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00041919-WTXWH\x00\x00\x00\x00\x01\x00\x00\x00\x01d\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00MEIA\x00\x00"
            devStatus = 0
            threadCnt = 0
            time.sleep(1)
            s.send(devLogoMsg)
            print("dev id:",id)
            hartCnt = 0
            while True:
                try:
                    time.sleep(0.01)
                    threadCnt += 1
                    if Qd.qsize() > 0: #收到报文
                        data = Qd.get(block=False)
                        sdata = data
                        #print ('<<<',binascii.b2a_hex(sdata),'\n',sdata)
                        if data[6] == 0x03 and data[7] == 0x20:#登录成功
                            devStatus = 1
                            print ("设备",id,"登录成功")
                            s.send(devheartbeatMsg)
                            s.send(devheartbeatMsg)
                            s.send(devheartbeatMsg)
                        if devStatus == 1:#设备已经登录
                            if data[6] == 0x01 and data[7] == 0x00:#收到心跳应答
                                #print(hartCnt,id,"接收到心跳应答")
                                pass
                            if data[6] == 0x00 and data[7] == 0xa8:
                                s.send(devWorkStatusMsg)
                                if data[8] == 0x02:
                                    print ("系统撤防")
                                    s.send(xmlAlramSting2)#撤防
                                if data[8] == 0x01:
                                    print ("系统在家布防")
                                    s.send(xmlAlramSting)#在家布防
                                if data[8] == 0x00:
                                    print ("系统外出布防")
                                    s.send(xmlAlramSting1)#外出布防
                                if data[8] == 0x03:
                                    print ("清除报警")

                    elif devStatus == 1:#设备已经登录,没有收到报文时
                        if threadCnt % 4500 == 0:
                            s.send(devheartbeatMsg)
                            #print(hartCnt,id,"发送心跳")
                            hartCnt += 1
                            pass
                        '''
                        if threadCnt %1000 == 0:
                            s.send(xmlAlramSting3)
                            print("发送报警")
                        '''
                        #print(threadCnt)
                except BaseException:
                    try:
                        s.close()
                    finally:
                        break
                        print("重连服务器")
        except BaseException:
            pass

def createDevs():
    cmdq = []
    file = open("111.data","r")
    for line in range(0,30):
        id = file.readline(9)
        #print("line:",line,id)
        id = id.replace("\n","")

        cq = queue.Queue(100)
        cmdq.append(cq)
        createDev(id,cq)#创建设备
    file.close()
    th = threading.Thread(target=cmdThread,args=(cmdq,))
    th.start()

def createDev(id,cq=None):
    #os.system("ipconfig/flushdns")
    recvBuf = queue.Queue(100)

    th = threading.Thread(target=processData,args=(cq,recvBuf,id))
    th.start()

def cmdThread(cq):
    time.sleep(1)
    while True:
        cmd = input("输入1开始>>:")
        for q in cq:
            q.put(cmd)

if __name__ == "__main__":
    #createDev("gs1mgqJa")
    createDevs()

